/* 
 *  <copyright file="TimeToLive.cs" company="Wesley Jowitt">
 *  
 *  SobrietyEngine: Copyright (c) 2011 Wesley Jowitt
 *  
 *  This software is distributed under a software license.
 *   * As of the creation time of this file, the license in use is the Microsoft Permissive License (Ms-PL) 
 *    * The license can be viewed at:
 *     * License.Txt in the root folder of this project
 *      * http://sobrietyengine.codeplex.com/license
 *       * http://www.microsoft.com/opensource/licenses.mspx
 *       
 *  </copyright>
 *   */

using System;

using Microsoft.Xna.Framework;
using SobrietyEngine.Events.Actor;

namespace SobrietyEngine.Components.Misc
{
    public class TimeToLive:BaseComponent
    {
        float timeInMs = 0.0f;
        public float TimeInMs
        {
            get { return timeInMs; }
            set { timeInMs = value; if (timeInMs > 0.0f) { allowUpdate = true; } }
        }

        private Boolean allowUpdate = true;

        public TimeToLive()
            : base()
        {
            
        }

        public TimeToLive(float timeToLiveInSeconds)
            : base()
        {
            timeInMs = timeToLiveInSeconds * 1000;
        }


        public TimeToLive(int timeToLiveInMs)
            : base()
        {
            timeInMs = timeToLiveInMs;
        }

        public override void Update(GameTime elapsedTime)
        {
            //allow update can be used for something like a timeInMs bomb with a on/off switch
            if (allowUpdate == true)
            {                
                TimeInMs -= elapsedTime.ElapsedGameTime.Milliseconds;
                if (timeInMs <= 0.0f)
                {
                    //dont need to update this component anymore
                    allowUpdate = false;

                    //marked for removel means we will delete this actor on the next pass through the scene update
                    Actor.MarkedForRemoval = true;
                    Actor.EventRouter.RaiseEvent(this, new ActorDied(Actor.Guid, null));
                }
            }
        }
    }
}